<template>
  <div class="p-4">
    <el-page-header @back="goBack" content="用户商品管理" />
    
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <span>用户信息</span>
          <el-button @click="refresh" icon="Refresh">刷新</el-button>
        </div>
      </template>
      <div class="flex items-center">
        <img 
          src="https://picsum.photos/seed/user123/80/80" 
          alt="用户头像" 
          class="w-16 h-16 rounded-full mr-4 object-cover"
        >
        <div>
          <p class="text-lg font-medium">{{ userInfo.username }}</p>
          <p class="text-gray-500 text-sm">注册时间: {{ userInfo.registerTime }}</p>
        </div>
      </div>
    </el-card>
    
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <span>商品筛选</span>
          <el-button @click="resetFilters" type="text">重置</el-button>
        </div>
      </template>
      <el-form :inline="true" :model="filters" class="flex flex-wrap gap-3">
        <el-form-item label="商品名称">
          <el-input v-model="filters.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filters.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="上架" value="active" />
            <el-option label="下架" value="inactive" />
            <el-option label="审核中" value="pending" />
            <el-option label="已拒绝" value="rejected" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格范围">
          <el-input-number v-model="filters.minPrice" placeholder="最低价" clearable style="width: 100px" />
          <span class="mx-2">-</span>
          <el-input-number v-model="filters.maxPrice" placeholder="最高价" clearable style="width: 100px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card>
      <template #header>
        <div class="flex justify-between items-center">
          <span>商品列表</span>
          <div class="flex items-center">
            <el-radio-group v-model="viewMode">
              <el-radio-button label="list">列表视图</el-radio-button>
              <el-radio-button label="grid">网格视图</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>
      
      <el-empty v-if="products.length === 0" description="暂无商品数据" />
      
      <el-table v-else-if="viewMode === 'list'" :data="products" stripe border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="商品信息" width="300">
          <template #default="scope">
            <div class="flex items-center">
              <img 
                :src="scope.row.images[0] || 'https://picsum.photos/seed/product'+scope.row.id+'/80/80'" 
                alt="商品图片" 
                class="w-12 h-12 rounded object-cover mr-3"
              >
              <div>
                <p class="font-medium">{{ scope.row.name }}</p>
                <p class="text-gray-500 text-sm">{{ scope.row.category }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            <span class="font-medium">¥{{ scope.row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag 
              :type="statusMap[scope.row.status].type"
              :effect="statusMap[scope.row.status].effect || 'light'"
            >
              {{ statusMap[scope.row.status].label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="text" size="small" @click="viewProduct(scope.row.id)">查看</el-button>
            <el-button type="text" size="small" @click="editProduct(scope.row.id)">编辑</el-button>
            <el-button 
              type="text" 
              size="small" 
              :type="scope.row.status === 'active' ? 'danger' : 'primary'"
              @click="toggleStatus(scope.row)"
            >
              {{ scope.row.status === 'active' ? '下架' : '上架' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
        <el-card 
          v-for="product in products" 
          :key="product.id"
          class="border hover:shadow-md transition-shadow"
        >
          <div class="relative">
            <img 
              :src="product.images[0] || 'https://picsum.photos/seed/product'+product.id+'/300/200'" 
              alt="商品图片" 
              class="w-full h-48 object-cover rounded-t"
            >
            <el-tag 
              class="absolute top-2 right-2"
              :type="statusMap[product.status].type"
              :effect="statusMap[product.status].effect || 'light'"
            >
              {{ statusMap[product.status].label }}
            </el-tag>
          </div>
          <div class="p-3">
            <h3 class="font-medium text-gray-800 mb-1 line-clamp-1">{{ product.name }}</h3>
            <p class="text-gray-500 text-sm mb-2 line-clamp-2">{{ product.description }}</p>
            <div class="flex justify-between items-center">
              <span class="font-medium text-lg">¥{{ product.price.toFixed(2) }}</span>
              <el-button size="mini" type="primary" @click="viewProduct(product.id)">查看详情</el-button>
            </div>
          </div>
        </el-card>
      </div>
      
      <div class="mt-4 flex justify-end">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const route = useRoute()

const userInfo = ref({
  id: 1,
  username: '张三',
  avatar: 'https://picsum.photos/seed/user123/200/200',
  registerTime: '2023-01-15 08:30:00',
  email: 'zhangsan@example.com',
  phone: '13800138000'
})

const products = ref([
  {
    id: 1,
    name: '高品质无线耳机',
    description: '主动降噪，音质出色，续航长达30小时',
    price: 899.00,
    category: '电子数码',
    status: 'active',
    createTime: '2023-03-10 14:25:00',
    images: ['https://picsum.photos/seed/headphone1/300/200']
  },
  {
    id: 2,
    name: '专业摄影相机',
    description: '2410万像素，5轴防抖，4K视频录制',
    price: 5699.00,
    category: '电子数码',
    status: 'active',
    createTime: '2023-02-20 09:15:00',
    images: ['https://picsum.photos/seed/camera1/300/200']
  },
  {
    id: 3,
    name: '智能手表',
    description: '心率监测，睡眠分析，50米防水',
    price: 1299.00,
    category: '智能设备',
    status: 'pending',
    createTime: '2023-03-15 16:40:00',
    images: ['https://picsum.photos/seed/watch1/300/200']
  },
  {
    id: 4,
    name: '机械键盘',
    description: '红轴，全键无冲，RGB背光',
    price: 499.00,
    category: '电脑配件',
    status: 'inactive',
    createTime: '2023-01-25 11:30:00',
    images: ['https://picsum.photos/seed/keyboard1/300/200']
  },
  {
    id: 5,
    name: '游戏鼠标',
    description: '16000DPI，RGB灯光，可编程按键',
    price: 249.00,
    category: '电脑配件',
    status: 'rejected',
    createTime: '2023-03-05 10:05:00',
    images: ['https://picsum.photos/seed/mouse1/300/200']
  }
])

const statusMap = {
  active: { label: '上架', type: 'success' },
  inactive: { label: '下架', type: 'info' },
  pending: { label: '审核中', type: 'warning' },
  rejected: { label: '已拒绝', type: 'danger' }
}

const filters = reactive({
  name: '',
  status: '',
  minPrice: null,
  maxPrice: null
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 100
})

const viewMode = ref('list')

const goBack = () => {
  router.push({ name: 'user-list' })
}

const refresh = () => {
  fetchProducts()
}

const resetFilters = () => {
  filters.name = ''
  filters.status = ''
  filters.minPrice = null
  filters.maxPrice = null
  fetchProducts()
}

const search = () => {
  pagination.currentPage = 1
  fetchProducts()
}

const fetchProducts = async () => {
  try {
    // 模拟API请求
    // const { data } = await axios.get('/api/products', {
    //   params: {
    //     userId: route.params.id,
    //     ...filters,
    //     page: pagination.currentPage,
    //     pageSize: pagination.pageSize
    //   }
    // })
    // products.value = data.items
    // pagination.total = data.total
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  }
}

const viewProduct = (id) => {
  router.push({ name: 'product-detail', params: { id } })
}

const editProduct = (id) => {
  router.push({ name: 'product-edit', params: { id } })
}

const toggleStatus = async (product) => {
  try {
    const action = product.status === 'active' ? '下架' : '上架'
    const { value } = await ElMessageBox.confirm(
      `确定要${action}该商品吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (value) {
      // 模拟API请求
      // await axios.post(`/api/products/${product.id}/${product.status === 'active' ? 'deactivate' : 'activate'}`)
      
      product.status = product.status === 'active' ? 'inactive' : 'active'
      ElMessage.success(`${action}成功`)
    }
  } catch (error) {
    // 用户取消操作
  }
}

const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  fetchProducts()
}

const handleCurrentChange = (newPage) => {
  pagination.currentPage = newPage
  fetchProducts()
}

onMounted(() => {
  fetchUserInfo()
  fetchProducts()
})

const fetchUserInfo = async () => {
  try {
    // 模拟API请求
    // const { data } = await axios.get(`/api/users/${route.params.id}`)
    // userInfo.value = data
  } catch (error) {
    ElMessage.error('获取用户信息失败')
  }
}
</script>

<style scoped>
/* 自定义样式 */
</style>    